/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Visao;

import Controle.Controlador;
import Modelo.Acompanhamento;
import java.awt.Color;
import java.awt.HeadlessException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Eder
 */
public class AddAcompanhamento extends javax.swing.JFrame {
    DefaultTableModel modelo;
    TableRowSorter sorter;
    NovoPedido np;
    Acompanhamento acomp;

    public AddAcompanhamento(){
        initComponents();
    }

    /**
     * Creates new form AddAcompanhamento
     */
    
    public AddAcompanhamento(NovoPedido np) {
        initComponents();
        this.np=np;
        modelo = (DefaultTableModel) jtabelaAcompanhamentos.getModel();
        sorter = new TableRowSorter(modelo);
        jScrollPane1. getViewport().setBackground(Color.WHITE);
//        jtabelaAcompanhamentos.getColumnModel().getColumn( 0 ).setMaxWidth( 0 );  
//        jtabelaAcompanhamentos.getColumnModel().getColumn( 0 ).setMinWidth( 0 );  
//        jtabelaAcompanhamentos.getTableHeader().getColumnModel().getColumn( 0 ).setMaxWidth( 0 );  
//        jtabelaAcompanhamentos.getTableHeader().getColumnModel().getColumn( 0 ).setMinWidth( 0 );
        
        imprimeDadosTabelas(carregarDadosBD());
    }
    
    public AddAcompanhamento(NovoPedido np, Acompanhamento ap) {
        initComponents();
        this.acomp= ap;
        this.np=np;
        modelo = (DefaultTableModel) jtabelaAcompanhamentos.getModel();
        sorter = new TableRowSorter(modelo);
        jScrollPane1. getViewport().setBackground(Color.WHITE);
//        jtabelaAcompanhamentos.getColumnModel().getColumn( 0 ).setMaxWidth( 0 );  
//        jtabelaAcompanhamentos.getColumnModel().getColumn( 0 ).setMinWidth( 0 );  
//        jtabelaAcompanhamentos.getTableHeader().getColumnModel().getColumn( 0 ).setMaxWidth( 0 );  
//        jtabelaAcompanhamentos.getTableHeader().getColumnModel().getColumn( 0 ).setMinWidth( 0 );
        
        imprimeDadosTabelas(carregarDadosBD());
        setDadosVisao(ap);
    }
    
    private void setDadosVisao(Acompanhamento ap){
        for (int i = 0; i < jtabelaAcompanhamentos.getRowCount(); i++) {
            if(jtabelaAcompanhamentos.getValueAt(i, 0)==ap.getCodigo()){
                jtabelaAcompanhamentos.setRowSelectionInterval(i, i);
                break;
            }
        }
    }
    
    private ArrayList<Acompanhamento> carregarDadosBD(){
        ArrayList<Acompanhamento> acomp = new ArrayList<>();
        if(Controlador.carregarDadosBD_Acompanhamentos(acomp)){
            return acomp;
        }
        return null;
    }
    
    private void imprimeDadosTabelas(ArrayList<Acompanhamento> acomp) {
        // Adiciona uma nova linha em branco no modelo  
        int linhaTabela = 0;
        //jTtabelaRP.setRowSorter(null); // desabilita o filtro
        
        for (int i = 0; i < acomp.size(); i++) {            
            if (jtabelaAcompanhamentos.getRowCount() <= linhaTabela) {
                modelo.addRow(new String[]{"", ""});
            }
            jtabelaAcompanhamentos.setValueAt(acomp.get(i).getCodigo(), linhaTabela, 0);
            jtabelaAcompanhamentos.setValueAt(acomp.get(i).getNome(), linhaTabela, 1);
            jtabelaAcompanhamentos.setValueAt(acomp.get(i).getValor(), linhaTabela, 2);
            linhaTabela++;
        }
        removeLinhasInutilizadas(linhaTabela);
        jfiltroTFKeyReleased(null);
    }
    
    public void atualizaTabela(){
        imprimeDadosTabelas(carregarDadosBD());
    }
    
    public void removeLinhasInutilizadas(int linhaTabela){
        for (int i = linhaTabela; i < jtabelaAcompanhamentos.getRowCount(); i++) {
            modelo.removeRow(i);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jtabelaAcompanhamentos = new javax.swing.JTable();
        jconcluirB = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jfiltroTF = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Adicionar Acompanhamento");

        jtabelaAcompanhamentos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cod", "Produto", "Valor"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jtabelaAcompanhamentos.setMinimumSize(new java.awt.Dimension(100, 0));
        jScrollPane1.setViewportView(jtabelaAcompanhamentos);

        jconcluirB.setText("Concluir");
        jconcluirB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jconcluirBActionPerformed(evt);
            }
        });

        jLabel3.setText("Filtro:");

        jfiltroTF.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jfiltroTFKeyReleased(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 3, 12)); // NOI18N
        jLabel4.setText("Acompanhamentos");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jfiltroTF, javax.swing.GroupLayout.DEFAULT_SIZE, 348, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGap(290, 290, 290)
                                .addComponent(jconcluirB, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(136, 136, 136)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jfiltroTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jconcluirB)
                .addContainerGap(16, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-416)/2, (screenSize.height-341)/2, 416, 341);
    }// </editor-fold>//GEN-END:initComponents

    private void jconcluirBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jconcluirBActionPerformed
        // Botão Concluir 
        try {
            if(this.acomp==null){
                int linha = jtabelaAcompanhamentos.getSelectedRow();
                if (linha != -1) {
                    Acompanhamento acomp = new Acompanhamento();
                    acomp.setCodigo(jtabelaAcompanhamentos.getValueAt(linha, 0).toString());
                    acomp.setNome(jtabelaAcompanhamentos.getValueAt(linha, 1).toString());
                    acomp.setValor(jtabelaAcompanhamentos.getValueAt(linha, 2).toString());

                    
                    Controlador.getPedidoAtual().addItem(acomp);
                    System.out.println("Adicionou o Acompanhamento!");
                    np.atualizaTabela();
                    this.setVisible(false);
                } else {
                    throw new Exception("Selecione a linha do Acompanhamento desejado");
                }
            }else{
                int linha = jtabelaAcompanhamentos.getSelectedRow();
                if (linha != -1) {
                    
                    this.acomp.setCodigo(jtabelaAcompanhamentos.getValueAt(linha, 0).toString());
                    this.acomp.setNome(jtabelaAcompanhamentos.getValueAt(linha, 1).toString());
                    this.acomp.setValor(jtabelaAcompanhamentos.getValueAt(linha, 2).toString());

                    // ainda tem mais pra faze.... =/
                    
                    System.out.println("Editou o Acompanhamento!");
                    np.atualizaTabela();
                    this.setVisible(false);
                } else {
                    throw new Exception("Selecione a linha do Acompanhamento desejado");
                }
            }
                
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }//GEN-LAST:event_jconcluirBActionPerformed

    private void jfiltroTFKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jfiltroTFKeyReleased
        // Filtro:
        sorter.setRowFilter(RowFilter.regexFilter(jfiltroTF.getText().toUpperCase()));
        jtabelaAcompanhamentos.setRowSorter(sorter);
    }//GEN-LAST:event_jfiltroTFKeyReleased

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AddAcompanhamento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AddAcompanhamento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AddAcompanhamento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AddAcompanhamento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new AddAcompanhamento().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jconcluirB;
    private javax.swing.JTextField jfiltroTF;
    private javax.swing.JTable jtabelaAcompanhamentos;
    // End of variables declaration//GEN-END:variables
}
